// 创建地址
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const { receiver, phoneNumber, region, detail, isDefault } = event
  
  // 直接使用openid作为用户标识
  if (!wxContext.OPENID) {
    return {
      success: false,
      message: '用户未登录'
    }
  }
  
  const userOpenid = wxContext.OPENID

  // 参数验证
  if (!receiver || !phoneNumber || !region || !detail) {
    return {
      success: false,
      message: '缺少必要参数'
    }
  }

  // 验证手机号格式
  const phoneRegex = /^1[3-9]\d{9}$/
  if (!phoneRegex.test(phoneNumber)) {
    return {
      success: false,
      message: '手机号格式不正确'
    }
  }

  // 验证省市区
  if (!Array.isArray(region) || region.length !== 3 || !region[0] || !region[1] || !region[2]) {
    return {
      success: false,
      message: '请选择完整的省市区'
    }
  }

  try {
    const now = new Date()
    
    // 如果设置为默认地址，先将用户其他地址的默认状态设为false
    if (isDefault) {
      await db.collection('addresses')
        .where({
          userId: userOpenid
        })
        .update({
          data: {
            isDefault: false,
            updatedAt: now
          }
        })
    }

    // 创建新地址
    const result = await db.collection('addresses').add({
      data: {
        userId: userOpenid,
        receiver: receiver.trim(),
        phoneNumber: phoneNumber.trim(),
        region: region,
        detail: detail.trim(),
        isDefault: isDefault || false,
        createdAt: now,
        updatedAt: now
      }
    })

    return {
      success: true,
      message: '地址添加成功',
      data: {
        _id: result._id
      }
    }
  } catch (error) {
    console.error('创建地址失败:', error)
    return {
      success: false,
      message: '创建地址失败',
      error: error.message
    }
  }
}